using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class NetworkStart : MonoBehaviour {
	public GameObject sunLight;
	public string connectionIP = "127.0.0.1";
	public int connectionPort = 25001;
	public Transform playerPrefab; 
	public RespawnHandler respawnPlayerHandler;
	public NetworkEntityMgr networkEntityMgr;
	public DuctTaper ductTapeMgr;
	
	public GUIHealthBar healthbar;
	public PlayerGUI playergui;
	public Camera buildScreenCamera;
	
	public StartMenu startmenu;
	
	public Texture2D disconnectButtonTexture;
	
	public float restartTime = 15f;
	private float restartElapsed = 0f;
	private bool restart = false;
	
	private Texture2D startScreenBackground;
	
	
	
	private Dictionary<NetworkPlayer,NetworkViewID> playerDictionary = new Dictionary<NetworkPlayer,NetworkViewID>();
	
	void Awake() {
		DontDestroyOnLoad(transform.gameObject);
	}
	
	void Start() {
		/*if (GameObject.Find("GUIHandler") != null)	
			startmenu = GameObject.Find("GUIHandler").GetComponent<StartMenu>();
		*/
				
	}
	
	void Update(){
		if(restart){
			restartElapsed += Time.deltaTime;
			if(restartElapsed>restartTime){
				Network.Disconnect();
				IDManager.inst().clear();
				Application.LoadLevel(0);
			}
		}
	}
	
	void OnGUI()
    {
		if (startScreenBackground == null){
			startScreenBackground = new Texture2D(1,1);
			startScreenBackground.SetPixel(1,1,Color.black);
			startScreenBackground.Apply();
		}
	        if (Network.peerType == NetworkPeerType.Disconnected)
	        {
			// && (!startmenu.getActive()||startmenu != null
				if ((startmenu != null && !startmenu.getActive()) || startmenu == null){
					GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),startScreenBackground,ScaleMode.StretchToFill);
					GUI.Label(new Rect(Screen.width/2-60, Screen.height/2+50, 300, 20), "Status: Disconnected");
					GUI.Label(new Rect(Screen.width/2-60, Screen.height/2+75, 300, 20),"Your IP: " + Network.player.ipAddress);
					GUILayout.BeginHorizontal();
					GUILayout.Space(400);
					//connectionIP = GUILayout.TextField(connectionIP,GUILayout.MinWidth(100));
					connectionIP = GUI.TextField(new Rect(Screen.width/2-60, Screen.height/2+2,120,22),connectionIP);
		            if (GUI.Button(new Rect(Screen.width/2-60, Screen.height/2-20, 120, 20), "Client Connect"))
		            {
		                Network.Connect(connectionIP, connectionPort);
		            }
		            if (GUI.Button(new Rect(Screen.width/2-60, Screen.height/2+25, 120, 20), "Initialize Server"))
		            {
		                Network.InitializeServer(32, connectionPort, false);
		            }
				}
	        }
	        else if (Network.peerType == NetworkPeerType.Client)
	        {
	            GUI.Label(new Rect(10, 10, 300, 20), "Status: Connected as Client");
	            if (GUI.Button(new Rect(10, 30, 120, 20), "Disconnect"))
	            {
					//networkView.RPC("playerLeft",RPCMode.All,myNetworkId);
	                Network.Disconnect(200);
	            }
	        }
	        else if (Network.peerType == NetworkPeerType.Server)
	        {
				//GUI.Label(new Rect(400,10,200,20),Network.player.ipAddress);
	            //GUI.Label(new Rect(10, 10, 300, 20), "Status: Connected as Server");
				if (disconnectButtonTexture != null)
					if (GUI.Button(new Rect(2,2,40,40),disconnectButtonTexture,GUIStyle.none)){
						Network.Disconnect();
						IDManager.inst().clear();
						Application.LoadLevel(0);
				}
				
	            /*if (GUI.Button(new Rect(10, 30, 120, 20), "Disconnect"))
			    {
					//networkView.RPC("playerLeft",RPCMode.All,myNetworkId);
	                Network.Disconnect(200);
	            }*/
	        }
    }
	
	void OnPlayerDisconnected(NetworkPlayer player) {
		NetworkViewID id;
		id = playerDictionary[player];
		ScoreListener.inst().notify(new ScoreEvent(IDManager.inst().findByNid(id),ScoreAction.REMOVE,0));
		
		Debug.Log("Clean up after player " + player);
		Network.RemoveRPCs(player);        
		Network.DestroyPlayerObjects(player);    
	}
	
	void OnPlayerConnected(NetworkPlayer player){
//		networkEntityMgr.syncScoreBoard();
	}
	
	void OnDisconnectedFromServer(NetworkDisconnection info) {
//		networkEntityMgr.clearScore();
		
		NetworkView[] networkViews = (NetworkView[]) Object.FindObjectsOfType(typeof(NetworkView));
		
		// Go through all Network Views.
		foreach (NetworkView view in networkViews) {
			if (view.GetComponent<NetworkEntityMgr>() == null) {
				Destroy(view.gameObject);
			}
		}
	}

	void OnServerInitialized() {
		//SpawnPlayer();
		if (startmenu != null)
			startmenu.setActive(true);
		else
			SpawnPlayer();
	}
	
	void OnConnectedToServer() {
		if (startmenu != null)
			startmenu.setActive(true);
		else
			SpawnPlayer();
		
	}
	
	public void SpawnPlayer() {
		Transform myTransform = (Transform) Network.Instantiate(playerPrefab, transform.position, transform.rotation, 0);
		GameObject player = myTransform.gameObject;
		if (sunLight != null)
			sunLight.GetComponent<LightColor>().setCamera(player.transform.FindChild("FPSCamera").gameObject);
		if(respawnPlayerHandler != null)
			player.GetComponent<Damagable>().setRespawnHandler(respawnPlayerHandler);
		if(networkEntityMgr != null)
			player.GetComponent<BuildScreen>().setNetworkEntityMgr(networkEntityMgr);
		if(ductTapeMgr != null)
			player.GetComponent<BuildScreen>().setDuctTapeMgr(ductTapeMgr);
		if(healthbar != null)
			player.GetComponent<BuildScreen>().setHealthbar(healthbar);
		if(playergui != null)
			player.GetComponent<BuildScreen>().setPlayerGUI(playergui);
		if(buildScreenCamera != null)
			player.GetComponent<BuildScreen>().setBuildScreenBackground(buildScreenCamera);
		
		if (player == null) {
			Debug.Log ("404. Player not found.");
		}
//		ScoreListener.inst().notify(new ScoreEvent(player.GetComponent<NID>().getId(),ScoreAction.ADD,0));		
	}
	
	[RPC]
	void playerJoined(NetworkPlayer p, NetworkViewID id){
		playerDictionary.Add(p,id);
	}
	
		//START END GAME
	[RPC]
	public void startGameRPC(){
		SpawnPlayer();
		if(startmenu != null){
			startmenu.setActive(false);
		}
		if(Object.FindObjectOfType(typeof(GUIHealthBar)) != null){
			GUIHealthBar healthbar = Object.FindObjectOfType(typeof(GUIHealthBar)) as GUIHealthBar;
			healthbar.setDisplay (true);
		}
		LightColor  light = Object.FindObjectOfType(typeof(LightColor)) as LightColor;
		light.resetTime();
	}
	
	[RPC]
	public void endGameRPC(){
		//End Game
		Debug.Log("Ending Game");
		
		PlayerState pl = null;
		NetworkGamePlayer[] players = (NetworkGamePlayer[]) Object.FindObjectsOfType(typeof(NetworkGamePlayer)) as NetworkGamePlayer[];
		for(int i = 0;i < players.Length;i++){
			if(players[i].enabled){
				pl = players[i].gameObject.GetComponent<PlayerState>();
				players[i].disable();
				players[i].gameObject.GetComponentInChildren<MiniMap>().enabled = false;
			}
		}
		restart = true;
		

		
		
		GUIScoreMeter meter = Object.FindObjectOfType(typeof(GUIScoreMeter)) as GUIScoreMeter;
		if(meter.isWinner()){
			Debug.Log(pl);
			if(pl != null)
				Listeners.inst().notify(Channel.ON_WON_GAME,pl);
		}else{
			Listeners.inst().notify(Channel.ON_LOST_GAME,pl);
		}
		meter.endGame();
	}
	
}
